// $Id: $
package Client_Server;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import Communication.Buffer;
import Communication.Message;
import Communication.ClientReceiver;
import Communication.ClientSender;

/**
 * @author casidiablo
 * 
 */
public class Chat extends JFrame implements ActionListener, Observer {
    private JTextField cajaEnviar;
    private JButton botonEnviar;
    private JLabel estado;
    private JTextArea board;

    public Chat ( ) {
        super ( "Cliente RMI" );
        getContentPane ( ).setLayout ( new BorderLayout ( ) );
        cajaEnviar = new JTextField ( );
        cajaEnviar.addActionListener ( this );
        botonEnviar = new JButton ( "Enviar" );
        botonEnviar.addActionListener ( this );
        estado = new JLabel ( "Estado..." );
        JPanel pane = new JPanel ( ); 
        pane.setLayout ( new BorderLayout ( ) );
        
        board = new JTextArea ( );
        board.setLineWrap ( true );
		
		board.setEditable ( false );
		JScrollPane scroll = new JScrollPane ( board );
		pane.add ( cajaEnviar );
        pane.add ( botonEnviar, BorderLayout.EAST );
        pane.add ( estado, BorderLayout.SOUTH );
        getContentPane ( ).add ( scroll );
        getContentPane ( ).add( pane, BorderLayout.SOUTH );

        JFrame.setDefaultLookAndFeelDecorated ( true );
        setSize ( 300, 400 );
        setVisible ( true );
        setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
        
        registrar ( );
    }

    public void actionPerformed(ActionEvent e) {
        if ( !cajaEnviar.getText ( ).equals ( "" ) ) {
            enviarMensaje ( cajaEnviar.getText ( ) );
            cajaEnviar.setText ( "" );
        }
    }

    private void registrar ( ) {
        ClientSender.getInstance ( ).registrar ( );
    	ClientReceiver.abrirConexion ( );
        Buffer.getInstance ( ).addObserver ( this );
    }
    
    private void enviarMensaje ( String mensaje ) {
        //estado.setText ( "Enviando " + mensaje + " a " + direccionServidor + ":" + puertoServidor );
    	Message msg = new Message ( );
    	msg.setBody ( mensaje );
    	ClientSender.getInstance ( ).enviarMensaje ( msg );
        board.append ( "Me:" + msg.getBody ( ) + "\n" );
        estado.setText ( "El mensaje se ha enviado!!!" );
    }

    static public void main ( String args[] ) {
        new Chat ( );
    }

	public void update ( Observable obsevable, Object arg1 ) {
		Buffer buffer = (Buffer)obsevable;
		while ( !buffer.isEmpty ( ) ) {
			Message msg = buffer.getMessage ( );
			board.append ( msg.getFrom ( ).getNick ( ) + ": " + msg.getBody ( ) + "\n" );
		}
	}
}
// $Log: $